import { login, getUserInfo } from '@/api/Api/system/login'
import Cookies from 'js-cookie'

const user = {
    state: {
        token: '',
        name: '',
        username: '',
        avatar: '',
        gender: null,
        job: null,
        dept_id: null,
        entry_date: null
    },
    mutations: {
        SET_TOKEN(state, token) {
            state.token = token
        },
        SET_NAME(state, name) {
            state.name = name
        },
        SET_USERNAME(state, username) {
            state.username = username
        },
        SET_AVATAR(state, avatar) {
            state.avatar = avatar
        },
        SET_GENDER(state, gender) {
            state.gender = gender
        },
        SET_JOB(state, job) {
            state.job = job
        },
        SET_DEPT_ID(state, dept_id) {
            state.dept_id = dept_id
        },
        SET_ENTRY_DATE(state, entry_date) {
            state.entry_date = entry_date
        }
    },
    actions: {
        // 登录
        Login({ commit }, userInfo) {
            return new Promise((resolve, reject) => {
                login(userInfo).then(response => {
                    resolve(response)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        GetUserInfo({ commit }) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(response => {
                    if (response.data.code === 1) {
                        const data = response.data.data
                        commit('SET_NAME', data.name)
                        commit('SET_USERNAME', data.username)
                        commit('SET_AVATAR', data.image)
                        commit('SET_GENDER', data.gender)
                        commit('SET_JOB', data.job)
                        commit('SET_DEPT_ID', data.dept_id)
                        commit('SET_ENTRY_DATE', data.entry_date)
                        resolve(response)
                    }else if(response.data.code === 0){
                        reject(response.data.msg)
                    }
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        JudgeToken({ commit, state }) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(response => {
                    if (response.data.code === 1) {
                        resolve()
                    }else {
                        reject()
                    }
                })
            })
        },
        // 登出
        LogOut({ commit, state }) {
            return new Promise((resolve) => {
                commit('SET_TOKEN', '')
                localStorage.removeItem('userInfo')
                Cookies.remove('token')
                resolve()
            })
        }
    }
}

export default user